/*
 * Created on April 29, 2006
 *
 * Copyright (c) Patrick Armstrong 2002-2007. All Rights Reserved
 */
package org.dime.mine.bot;

import java.util.Iterator;
import java.util.List;

import org.dime.mine.bot.AwareBoard.AwareLocation;
import org.dime.mine.game.Board;
import org.dime.mine.game.actions.Mark;

/**
 * Contradiction is a solution algorithm. Contradiction tries to find a mark
 * configuration that, when set, results in an invalid board. This implies that
 * the conjectured mark cannot actually be a mine.
 * 
 * @author Owner
 */
public class Contradiction extends AbstractStrategy
{
    @Override
    public boolean execute(Board board)
    {
        AwareBoard awareBoard = new AwareBoard(board);
        for (AwareLocation location : awareBoard.getUnsolvedLocations())
        {
            if (isContradictable(location) && executeHelper(board, location))
                return true;
        }
        return false;
    }

    private boolean isContradictable(AwareBoard.AwareLocation location)
    {
        return location.getValue() == location.getMarks() + 1;
    }

    private boolean executeHelper(Board board, AwareBoard.AwareLocation location)
    {
        boolean flag = false;

        Investigation investigation = new Investigation(board, location);
        List<TestBoard> outcomes = investigation.getInvalidOutcomes();

        Iterator<TestBoard> it = outcomes.iterator();
        Mark[] assumption;
        Board.Location loc;
        while (it.hasNext())
        {
            assumption = it.next().getAssumption();
            if (assumption.length > 0)
            {
                loc = assumption[0].getLocation();
                board.open(loc.getRow(), loc.getColumn());
                flag = true;
            }
        }

        return flag;
    }
}
